<?php
/**
 * Created by PhpStorm.
 * User: chengchaogui
 * Date: 2017/8/9
 * Time: 10:33
 */

namespace App\Repository\Service;

use App\Framework\Config\SystemConstant;
use App\Framework\Enum\ManagerStatusEnum;
use App\Framework\Helper\TextHelper;
use App\Framework\Helper\TimeHelper;
use App\Framework\Helper\WebHelper;
use App\Framework\Model\LoginedManager;
use App\Framework\Model\Message;
use App\Framework\Session\ManagerSession;
use App\Models\Admin\Manager;
use App\Models\Admin\ManagerModule;
use App\Models\Admin\ManagerModulePermission;
use App\Models\Admin\ManagerRole;
use App\Models\Admin\ManagerRolePermission;
use App\Repository\Contract\IRzjhpAdmin;
use Illuminate\Support\Facades\DB;
use LogFacade;

class RzjhpAdminService implements IRzjhpAdmin
{
    //数据库连接
    private $connection = SystemConstant::RZJHPADMIN_CONNECTION;

    /**
     * 根据ID获取管理员
     * @param $id
     * @return mixed
     */
    public function getManager($id)
    {
        $m = Manager::find($id);
        return $m;
    }

    /**
     * 获取管理员列表
     * @param $form
     * @return mixed
     */
    public function getManagerList($form)
    {
        $managers = Manager::where(function ($query) use ($form) {
            if (!empty($form->id)) {
                $query->where('manager_id', $form->id);
            }
            if (!empty($form->username)) {
                $query->where('username', $form->username);
            }
        })->orderBy('manager_id', 'desc')->paginate(SystemConstant::ADMIN_TABLE_ROWS);

        return $managers;
    }

    /**
     * 添加管理员
     * @param $form
     * @return mixed
     */
    public function addManager($form)
    {
        if (strlen($form->username) < 5 || strlen($form->username) > 16) {
            return Message::setFalse('用户名必须是2-20个字符');
        }
        //验证用户名
        $valid = $this->managerIsExist($form->username);
        if ($valid) {
            return Message::setFalse('该用户名已被占用，请更换');
        }

        if (strlen($form->password) < 6 || strlen($form->password) > 16) {
            return Message::setFalse('登录密码长度必须为6-16位的字符串');
        }

        //验证登录密码
        if ($form->password != $form->confirmPassword) {
            return Message::setFalse('两次输入的登录密码不一致');
        }

        $salt = TextHelper::getRandomStr(6);//生成加密盐
        $pwd = md5(md5($form->password) . $salt);//生成登录密码

        $manager = new Manager();
        $manager->status = $form->status;
        $manager->manager_role_id = $form->roleID;
        $manager->username = $form->username;
        $manager->password = $pwd;
        $manager->salt = $salt;
        $manager->real_name = $form->realName;
        $manager->create_date = TimeHelper::getNow();
        $manager->save();

        return Message::setTrue('添加成功');
    }

    /**
     * 修改管理员
     * @param $form
     * @return mixed
     */
    public function updateManager($form)
    {
        $manager = Manager::find($form->id);
        if (empty($manager)) {
            return Message::setFalse('管理员不存在');
        }

        if (!empty($form->username) && $form->username != $manager->username) {
            //验证用户名
            $valid = $this->managerIsExist($form->username);
            if ($valid) {
                return Message::setFalse('该用户名已被占用，请更换');
            }

            $manager->username = $form->username;
        }

        if (!empty($form->password)) {
            if (len($form->password) < 6 || len($form->password) > 16) {
                return Message::setFalse('登录密码长度必须为6-16位的字符串');
            }

            if ($form->password != $form->confirmPassword) {
                return Message::setFalse('两次输入的登录密码不一致');
            }

            $password = md5(md5($form->password) . $manager->salt);
            $manager->password = $password;
        }

        if (!empty($form->roleID)) {
            $manager->manager_role_id = $form->roleID;
        }

        if (!empty($form->realName)) {
            $manager->real_name = $form->realName;
        }

        if ($form->status == ManagerStatusEnum::ENABLE || $form->status == ManagerStatusEnum::DISABLE) {
            $manager->status = $form->status;
        }

        $manager->save();
        return Message::setTrue('修改成功');
    }

    /**
     * 验证管理员是否已存在
     * @param $username
     * @return bool
     */
    public function managerIsExist($username)
    {
        $manager = Manager::where('username', $username)->first();
        if (!empty($manager)) {
            return true;
        }

        return false;
    }

    /**
     * 删除管理员
     * @param $id
     * @return mixed
     */
    public function deleteManager($id)
    {
        $manager = Manager::find($id);
        if (empty($manager)) {
            return Message::setFalse('删除失败');
        }

        if ($manager->role_id == SystemConstant::SUPER_MANAGER_ROLE_ID) {
            return Message::setFalse('不能对此管理员执行该操作');
        }

        $manager->delete();
        return Message::setTrue('删除成功');
    }

    /**
     * 管理员登录
     * @param $form
     * @return mixed
     */
    public function login($form)
    {
        $captcha = ManagerSession::getCaptcha();
        if (strtolower($captcha) != strtolower($form->captcha)) {
            return Message::setFalse('验证码不正确');
        }

        $manager = Manager::where('username', $form->username)->first();
        if (isset($manager) == false) {
            return Message::setFalse('登录账号不存在');
        }

        $pwd = md5(md5($form->password) . $manager->salt);
        $loginIP = WebHelper::getClientIP();
        $now = TimeHelper::getNow();
        if ($manager->password != $pwd) {
            LogFacade::storeLoginLog($manager->manager_id, $manager->username, '密码错误', $loginIP, $now);
            return Message::setFalse('登录密码不正确');
        }
        if ($manager->status != ManagerStatusEnum::ENABLE) {
            LogFacade::storeLoginLog($manager->manager_id, $manager->username, '拒绝冻结账号登录', $loginIP, $now);
            return Message::setFalse("该账号已被冻结");
        }

        $role = ManagerRole::where('manager_role_id', $manager->manager_role_id)->first();
        $modules = [];
        $permissions = [];
        if ($manager->manager_role_id == SystemConstant::SUPER_MANAGER_ROLE_ID) {
            $modules = ManagerModule::get();
        } else {
            //获取一级菜单
            $parentMenu = DB::connection($this->connection)->select('select * from manager_module where manager_module_id in (select distinct parent_id as module_id from manager_role_permission as mrp, manager_module as m where mrp.manager_role_id=? and m.manager_module_id=mrp.manager_module_id and m.parent_id <>0)order by sort', array($manager->manager_role_id));
            //获取二级菜单
            $subMenu = DB::connection($this->connection)->select('select m.manager_module_id,m.name,m.link,m.parent_id,m.layer,m.sort from manager_role_permission as mrp, manager_module as m where mrp.manager_role_id=? and m.manager_module_id=mrp.manager_module_id and m.parent_id <>0 order by m.sort', array($manager->manager_role_id));
            //获取权限
            $permissions = ManagerRolePermission::where('manager_role_id', $manager->manager_role_id)->get();

            //将一级菜单加入模块数组
            foreach ($parentMenu as $item) {
                array_push($modules, $item);
            }
            //将二级菜单加入模块数组
            foreach ($subMenu as $item) {
                array_push($modules, $item);
            }
        }

        //写入登录会话
        $logined = new LoginedManager($manager->manager_id, $manager->username, $manager->manager_role_id, $role->name, $manager->real_name, $modules, $permissions);
        ManagerSession::login($logined);

        //更新登录ip及时间
        $manager->last_login_ip = $loginIP;
        $manager->last_login_date = $now;
        $manager->save();
        //保存登录日志
        LogFacade::storeLoginLog($manager->manager_id, $manager->username, '登录成功', $loginIP, $now);
        return Message::setTrue('登录成功');
    }

    /**
     * 管理员登出
     * @return mixed
     */
    public function logout()
    {
        try {
            $loginIP = WebHelper::getClientIP();
            $now = TimeHelper::getNow();
            LogFacade::storeLoginLog(ManagerSession::getManagerID(), ManagerSession::getUsername(), '退出登录', $loginIP, $now);
            ManagerSession::logout();
        } catch (\Exception $e) {

        }
    }

    /**
     * 获取所有管理角色
     * @return mixed
     */
    public function getAllRole()
    {
        $roles = ManagerRole::get();
        return $roles;
    }

    /**
     * 根据ID获取管理员角色
     * @param $id
     * @return mixed
     */
    public function getRole($id)
    {
        $role = ManagerRole::where('manager_role_id', $id)->first();
        return $role;
    }

    /**
     * 添加角色
     * @param $form
     * @return mixed
     */
    public function addRole($form)
    {
        $role = new ManagerRole();
        $role->name = $form->name;
        $role->description = $form->description;

        $role->save();
    }

    /**
     * 修改角色
     * @param $form
     * @return mixed
     */
    public function updateRole($form)
    {
        $role = ManagerRole::where('manager_role_id', $form->roleID)->first();
        if (empty($role)) {
            return Message::setFalse('该角色不存在或已被删除');
        }

        $role->name = $form->name;
        $role->description = $form->description;

        $role->save();
        return Message::setTrue('修改成功');
    }

    /**
     * 根据角色id获取权限
     * @param $role_id
     * @return mixed
     */
    public function getRolePermission($role_id)
    {
        $permissions = ManagerRolePermission::where('manager_role_id', $role_id)->get();
        return $permissions;
    }

    /**
     * 设置管理员权限
     * @param $form
     * @return mixed
     */
    public function setPermission($form)
    {
        //先删除已有权限
        ManagerRolePermission::where('manager_role_id', $form->roleID)->delete();

        //保存修改后的权限
        foreach ($form->moduleID as $key => $val) {
            if (array_key_exists($val, $form->permissions)) {
                $perValues = $form->permissions[$val];
                $permissionValue = 0;
                foreach ($perValues as $index => $value) {
                    $permissionValue |= $value;
                }

                $mrp = new ManagerRolePermission();
                $mrp->manager_role_id = $form->roleID;
                $mrp->manager_module_id = $val;
                $mrp->permission_value = $permissionValue;

                $mrp->save();
            }
        }
    }

    /**
     * 获取模块列表
     * @param $module_ids
     * @return mixed
     */
    public function getModules()
    {
        $modules = ManagerModule::get();
        return $modules;
    }

    /**
     * 获取模块权限
     * @return mixed
     */
    public function getModulePermissions()
    {
        $permissions = ManagerModulePermission::get();
        return $permissions;
    }
}